package com.laolang.pluto.module.generator.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.laolang.pluto.common.persist.service.impl.BaseServiceImpl;
import com.laolang.pluto.module.generator.entity.GenTable;
import com.laolang.pluto.module.generator.mapper.GenTableMapper;
import com.laolang.pluto.module.generator.pojo.po.TableDetailPo;
import com.laolang.pluto.module.generator.pojo.po.TableInfoPo;
import com.laolang.pluto.module.generator.service.GenTableService;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author laolang
 * @date 2021-08-01 16:34
 */
@RequiredArgsConstructor
@Service
public class GenTableServiceImpl extends BaseServiceImpl<GenTableMapper, GenTable> implements GenTableService {

    private final GenTableMapper genTableMapper;

    @Override
    public PageInfo<GenTable> selectTableList(Integer page, Integer size, String tableName, String tableComment,
                                              Date startDate, Date endDate) {
        LambdaQueryWrapper<GenTable> wrapper = Wrappers.<GenTable>lambdaQuery();
        if (StrUtil.isNotBlank(tableName)) {
            wrapper.like(GenTable::getTableName, tableName);
        }
        if (StrUtil.isNotBlank(tableComment)) {
            wrapper.like(GenTable::getTableComment, tableComment);
        }
        if (null != startDate && null != endDate) {
            wrapper.between(GenTable::getCreateTime, startDate, endDate);
        }
        return listPage(page, size, wrapper);
    }

    @Override
    public PageInfo<TableInfoPo> selectTableInfoList(Integer page, Integer size, String tableName,
                                                     String tableComment) {
        PageHelper.startPage(page, size);
        return new PageInfo<>(genTableMapper.selectTableInfoList(tableName, tableComment));
    }

    @Override
    public TableInfoPo selectTableInfoByTableName(String tableName) {
        return genTableMapper.selectTableInfoByTableName(tableName);
    }

    @Override
    public List<TableDetailPo> selectTableDetail(String tableName) {
        List<TableDetailPo> pos = new ArrayList<>();
        List<Map<String, Object>> maps = genTableMapper.selectTableDetail(tableName);
        if (CollUtil.isNotEmpty(maps)) {
            pos = maps.stream().map(TableDetailPo::buildTableDetailPoFromMap).collect(Collectors.toList());
        }
        return pos;
    }
}
